package com.wpml.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.wpml.search.config.ElasticsearchConfig;
import com.wpml.search.constant.EsConstant;
import com.wpml.search.service.ISaveProductService;
import com.wpml.search.vo.SkuEsModel;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: wp
 * @date: 2019-09-02 10:43
 **/
@Service
@Slf4j
public class SaveProductServiceImpl implements ISaveProductService {

    @Resource
    RestHighLevelClient esClient;

    @Override
    public boolean save(List<SkuEsModel> skuEsList) throws IOException {
        // 构建批量保存请求
        BulkRequest bulkRequest = new BulkRequest();

        for (SkuEsModel esModel : skuEsList) {
            // 构建保存请求
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            indexRequest.id(String.valueOf(esModel.getSkuId()));

            indexRequest.source(JSON.toJSONString(esModel), XContentType.JSON);

            bulkRequest.add(indexRequest);
        }

        BulkResponse bulk = esClient.bulk(bulkRequest, ElasticsearchConfig.COMMON_OPTIONS);

        boolean b = bulk.hasFailures();
//        List<String> collect = Arrays.stream(bulk.getItems()).map(BulkItemResponse::getId).collect(Collectors.toList());

        Map<String, Object> ret = Arrays.stream(bulk.getItems()).collect(Collectors.toMap(BulkItemResponse::getId, BulkItemResponse::getResponse));
        log.warn("es 保存结果：{}", ret);
        return b;
    }
}
